const { ipcRenderer: ipc } = window.require && window.require('electron') || {}

/**
 * （将废弃，请使用 $ipcInvoke 代替）异步调用主函数
 * @param ipc
 * @param channel
 * @param param
 * @returns {Promise<unknown>}
 */
const call = (ipc, channel, param) => {
  return new Promise((resolve) => {
    ipc.once(channel, (event, result) => {
      console.log('[ipcRenderer] [call] result:', result)
      resolve(result)
    })
    ipc.send(channel, param)
  })
}

/**
 * 发送异步消息（invoke/handle 模型）
 * @param channel
 * @param param
 * @returns {Promise}
 */
const invoke = (channel, param) => {
    const message = ipc.invoke(channel, param);
    return message;
}

/**
 * 发送同步消息（send/on 模型）
 * @param channel
 * @param param
 * @returns {Any}
 */
const sendSync = (channel, param) => {
  const message = ipc.sendSync(channel, param);
  return message;
}

const methodCall = ($this,service,method,params,options,callback)=>{
  const invokeParams = {
    service:service,
    method: method,
    params: params
  }
  try {
    // if(options.actionLoadingField){
    //   $this[options.actionLoadingField] = true;
    // }
    invoke('controller.base.methodCall', invokeParams).then(res => {
      console.log('res:', res)
      if(res.success){
        if(options.msgTip){
          // $this.$message.success(res.message);
        }
      }else{
        if(options.msgTip){
          // $this.$message.error(res.message);
        }
      }
      if(callback){
        callback(res);
      }
    });
  }catch (e) {
    console.log(e);
    $this.$message.error("error="+e.toString());
    callback({success:false,message:e.toString()});
    // console.error("invoke error,detail="+JSON.stringify(e));
  }finally {
    // if(options.actionLoadingField){
    //   $this[options.actionLoadingField] = false;
    // }
  }
}

export {
  invoke as $ipcInvoke ,
  sendSync as $ipcSendSync,
  call as $ipcCall,
  methodCall as $methodCall,
  // $ipcCall = (channel, param) => call(ipc, channel, param)

}
// export default {
//
//   install(Vue) {
//     window.$ipc = ipc // 全局注入ipc
//     window.$ipcCall = (channel, param) => call(ipc, channel, param)
//     window.$ipcInvoke = invoke
//     window.$ipcSendSync = sendSync
//   }
// }
